﻿using System.Linq;

namespace TathamOddie.OpenSearchValidator.Logic.Tasks.Description
{
	public class FindOpenSearchDescriptionTask : IValidationTask
	{
		public ValidationTaskResult Validate(ValidationServices services, ValidationState state)
		{
			var result = new ValidationTaskResult();

			var linkTags = XhtmlParser.ParseTags(state.PageHtml, "link");
			var openSearchLinks = (
					from t in linkTags
					where t["type"] == "application/opensearchdescription+xml" && !string.IsNullOrEmpty(t["href"])
					select t["href"]
				).ToArray();

			if (openSearchLinks.Length == 0)
			{
				result.AddMessage(MessageType.Failure, "No OpenSearch descriptions were found on source page [{0}].", state.PageUri);
			}
			else
			{
                foreach (var descriptionPath in openSearchLinks)
                {
                    result.AddMessage(MessageType.Success, "Found an OpenSearch description link on source page [{0}] for [{1}].", state.PageUri, descriptionPath);
                    result.ChildTasks.Add(new RetrieveOpenSearchDescriptionTask(descriptionPath));
                }
			}

			return result;
		}
	}
}